package com.aijk.web.admin.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * XML对象转换工具 
 * @author 胡永伟
 * @version 1.0.0
 * @date 2015年10月15日 下午11:46:57
 * @since 1.0.0
 */
public final class XML {

	/**
	 * 将对象转成XML
	 * @param object 待转换对象
	 * @return XML字符串
	 * @throws JAXBException
	 */
	public static String toxml(Object object) 
			throws JAXBException {
		JAXBContext context = 
				JAXBContext.newInstance(object.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(
        		Marshaller.JAXB_FRAGMENT, true);
        Writer writer = new StringWriter();
        marshaller.marshal(object, writer);
        return writer.toString();
	}
	
	/**
	 * 将XML转成指定类型的对象
	 * @param xmlstr 待转换字符串
	 * @param clazz 要转成对象的类型
	 * @return 转换的对象
	 * @throws JAXBException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T parse(String xmlstr, Class<T> clazz) 
			throws JAXBException {
		 JAXBContext context = JAXBContext.newInstance(clazz);  
         Unmarshaller unmarshaller = context.createUnmarshaller();
         StringReader reader = new StringReader(xmlstr);
         return (T) unmarshaller.unmarshal(reader);  
	}
	
}
